package com.heima.demo9;

public class SellTicket implements Runnable {
    private int ticket = 100;
    private Object obj = new Object();

    //在SellTicket类中重写run()方法实现卖票，代码步骤如下
    @Override
    public void run() {
        while (true) {
            // 对可能有安全问题的代码加锁,多个线程必须使用同一把锁
            synchronized (obj){
                if(ticket>0){
                    try{
                        //t1休息100毫秒
                        Thread.sleep(100);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "正在出售第" + ticket + "张票");
                    ticket--; //tickets = 99;
                }

            }
            //t1出来了，这段代码的锁就被释放了
        }
    }
}
